package com.imporven.sell.convert;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imporven.sell.Collect.ArrayList;
import com.imporven.sell.domain.OrderDetail;
import com.imporven.sell.dto.OrderDTO;
import com.imporven.sell.enums.ResultEnum;
import com.imporven.sell.exception.SellException;
import com.imporven.sell.form.OrderForm;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

/**
 * @author imporven
 * @version 1.0.0
 * @date 2018-7-15 0:02
 * 订单form转dto转换器
 */
@Slf4j
public class OrderForm2OrderDTOConvert {
    public static OrderDTO convert(OrderForm orderForm) {
        OrderDTO orderDTO = new OrderDTO();

        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        orderDTO.setBuyerPhone(orderForm.getPhone());

        ObjectMapper mapper =  new ObjectMapper();
        List<OrderDetail> orderDetailList = ArrayList.newInstance();
        try {
            orderDetailList = mapper.readValue(orderForm.getItems(),new TypeReference<List<OrderDetail>>(){});
        } catch (IOException e) {
            log.error("【对象转换】错误，string={}",orderForm.getItems(),e);
            throw new SellException(ResultEnum.PARAMETER_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }
}
